<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>Module: ActiveRecord::Calculations::ClassMethods</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />
  <script type="text/javascript">
  // <![CDATA[

  function popupCode( url ) {
    window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
  }

  function toggleCode( id ) {
    if ( document.getElementById )
      elem = document.getElementById( id );
    else if ( document.all )
      elem = eval( "document.all." + id );
    else
      return false;

    elemStyle = elem.style;
    
    if ( elemStyle.display != "block" ) {
      elemStyle.display = "block"
    } else {
      elemStyle.display = "none"
    }

    return true;
  }
  
  // Make codeblocks hidden by default
  document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" )
  
  // ]]>
  </script>

</head>
<body>



    <div id="classHeader">
        <table class="header-table">
        <tr class="top-aligned-row">
          <td><strong>Module</strong></td>
          <td class="class-name-in-header">ActiveRecord::Calculations::ClassMethods</td>
        </tr>
        <tr class="top-aligned-row">
            <td><strong>In:</strong></td>
            <td>
                <a href="../../../files/vendor/rails/activerecord/lib/active_record/calculations_rb.html">
                vendor/rails/activerecord/lib/active_record/calculations.rb
                </a>
        <br />
            </td>
        </tr>

        </table>
    </div>
  <!-- banner header -->

  <div id="bodyContent">



  <div id="contextContent">



   </div>

    <div id="method-list">
      <h3 class="section-bar">Methods</h3>

      <div class="name-list">
      <a href="#M001627">average</a>&nbsp;&nbsp;
      <a href="#M001631">calculate</a>&nbsp;&nbsp;
      <a href="#M001632">construct_count_options_from_args</a>&nbsp;&nbsp;
      <a href="#M001626">count</a>&nbsp;&nbsp;
      <a href="#M001629">maximum</a>&nbsp;&nbsp;
      <a href="#M001628">minimum</a>&nbsp;&nbsp;
      <a href="#M001630">sum</a>&nbsp;&nbsp;
      </div>
    </div>

  </div>


    <!-- if includes -->

    <div id="section">





      


    <!-- if method_list -->
    <div id="methods">
      <h3 class="section-bar">Public Instance methods</h3>

      <div id="method-M001627" class="method-detail">
        <a name="M001627"></a>

        <div class="method-heading">
          <a href="#M001627" class="method-signature">
          <span class="method-name">average</span><span class="method-args">(column_name, options = {})</span>
          </a>
        </div>
      
        <div class="method-description">
          <p>
Calculates the <a href="ClassMethods.html#M001627">average</a> value on a
given column. The value is returned as a float. See <tt><a
href="ClassMethods.html#M001631">calculate</a></tt> for examples with
options.
</p>
<pre>
  Person.average('age')
</pre>
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001627-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001627-source">
<pre>
    <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/calculations.rb, line 54</span>
54:       <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">average</span>(<span class="ruby-identifier">column_name</span>, <span class="ruby-identifier">options</span> = {})
55:         <span class="ruby-identifier">calculate</span>(<span class="ruby-identifier">:avg</span>, <span class="ruby-identifier">column_name</span>, <span class="ruby-identifier">options</span>)
56:       <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>

      <div id="method-M001631" class="method-detail">
        <a name="M001631"></a>

        <div class="method-heading">
          <a href="#M001631" class="method-signature">
          <span class="method-name">calculate</span><span class="method-args">(operation, column_name, options = {})</span>
          </a>
        </div>
      
        <div class="method-description">
          <p>
This calculates aggregate values in the given column. Methods for <a
href="ClassMethods.html#M001626">count</a>, <a
href="ClassMethods.html#M001630">sum</a>, <a
href="ClassMethods.html#M001627">average</a>, <a
href="ClassMethods.html#M001628">minimum</a>, and <a
href="ClassMethods.html#M001629">maximum</a> have been added as shortcuts.
Options such as <tt>:conditions</tt>, <tt>:order</tt>, <tt>:group</tt>,
<tt>:having</tt>, and <tt>:joins</tt> can be passed to customize the query.
</p>
<p>
There are two basic forms of output:
</p>
<pre>
  * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float for AVG, and the given column's type for everything else.
  * Grouped values: This returns an ordered hash of the values and groups them by the &lt;tt&gt;:group&lt;/tt&gt; option.  It takes either a column name, or the name
    of a belongs_to association.

      values = Person.maximum(:age, :group =&gt; 'last_name')
      puts values[&quot;Drake&quot;]
      =&gt; 43

      drake  = Family.find_by_last_name('Drake')
      values = Person.maximum(:age, :group =&gt; :family) # Person belongs_to :family
      puts values[drake]
      =&gt; 43

      values.each do |family, max_age|
      ...
      end
</pre>
<p>
Options:
</p>
<ul>
<li><tt>:conditions</tt> - An SQL fragment like &quot;administrator = 1&quot;
or [ &quot;user_name = ?&quot;, username ]. See conditions in the intro to
<a href="../Base.html">ActiveRecord::Base</a>.

</li>
<li><tt>:include</tt>: Eager loading, see Associations for details. Since
calculations don&#8216;t load anything, the purpose of this is to access
fields on joined tables in your conditions, order, or group clauses.

</li>
<li><tt>:joins</tt> - An SQL fragment for additional joins like &quot;LEFT JOIN
comments ON comments.post_id = id&quot;. (Rarely needed). The records will
be returned read-only since they will have attributes that do not
correspond to the table&#8216;s columns.

</li>
<li><tt>:order</tt> - An SQL fragment like &quot;created_at DESC, name&quot;
(really only used with GROUP BY calculations).

</li>
<li><tt>:group</tt> - An attribute name by which the result should be grouped.
Uses the GROUP BY SQL-clause.

</li>
<li><tt>:select</tt> - By default, this is * as in SELECT * FROM, but can be
changed if you for example want to do a join, but not include the joined
columns.

</li>
<li><tt>:distinct</tt> - Set this to true to make this a distinct calculation,
such as SELECT COUNT(DISTINCT posts.id) &#8230;

</li>
</ul>
<p>
Examples:
</p>
<pre>
  Person.calculate(:count, :all) # The same as Person.count
  Person.average(:age) # SELECT AVG(age) FROM people...
  Person.minimum(:age, :conditions =&gt; ['last_name != ?', 'Drake']) # Selects the minimum age for everyone with a last name other than 'Drake'
  Person.minimum(:age, :having =&gt; 'min(age) &gt; 17', :group =&gt; :last_name) # Selects the minimum age for any family without any minors
  Person.sum(&quot;2 * age&quot;)
</pre>
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001631-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001631-source">
<pre>
     <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/calculations.rb, line 117</span>
117:       <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">calculate</span>(<span class="ruby-identifier">operation</span>, <span class="ruby-identifier">column_name</span>, <span class="ruby-identifier">options</span> = {})
118:         <span class="ruby-identifier">validate_calculation_options</span>(<span class="ruby-identifier">operation</span>, <span class="ruby-identifier">options</span>)
119:         <span class="ruby-identifier">column_name</span>     = <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:select</span>] <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:select</span>]
120:         <span class="ruby-identifier">column_name</span>     = <span class="ruby-value str">'*'</span> <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">column_name</span> <span class="ruby-operator">==</span> <span class="ruby-identifier">:all</span>
121:         <span class="ruby-identifier">column</span>          = <span class="ruby-identifier">column_for</span> <span class="ruby-identifier">column_name</span>
122:         <span class="ruby-identifier">catch</span> <span class="ruby-identifier">:invalid_query</span> <span class="ruby-keyword kw">do</span>
123:           <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:group</span>]
124:             <span class="ruby-keyword kw">return</span> <span class="ruby-identifier">execute_grouped_calculation</span>(<span class="ruby-identifier">operation</span>, <span class="ruby-identifier">column_name</span>, <span class="ruby-identifier">column</span>, <span class="ruby-identifier">options</span>)
125:           <span class="ruby-keyword kw">else</span>
126:             <span class="ruby-keyword kw">return</span> <span class="ruby-identifier">execute_simple_calculation</span>(<span class="ruby-identifier">operation</span>, <span class="ruby-identifier">column_name</span>, <span class="ruby-identifier">column</span>, <span class="ruby-identifier">options</span>)
127:           <span class="ruby-keyword kw">end</span>
128:         <span class="ruby-keyword kw">end</span>
129:         <span class="ruby-value">0</span>
130:       <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>

      <div id="method-M001626" class="method-detail">
        <a name="M001626"></a>

        <div class="method-heading">
          <a href="#M001626" class="method-signature">
          <span class="method-name">count</span><span class="method-args">(*args)</span>
          </a>
        </div>
      
        <div class="method-description">
          <p>
Count operates using three different approaches.
</p>
<ul>
<li>Count all: By not passing any parameters to <a
href="ClassMethods.html#M001626">count</a>, it will return a <a
href="ClassMethods.html#M001626">count</a> of all the rows for the model.

</li>
<li>Count using column: By passing a column name to <a
href="ClassMethods.html#M001626">count</a>, it will return a <a
href="ClassMethods.html#M001626">count</a> of all the rows for the model
with supplied column present

</li>
<li>Count using options will find the row <a
href="ClassMethods.html#M001626">count</a> matched by the options used.

</li>
</ul>
<p>
The third approach, <a href="ClassMethods.html#M001626">count</a> using
options, accepts an option hash as the only parameter. The options are:
</p>
<ul>
<li><tt>:conditions</tt>: An SQL fragment like &quot;administrator = 1&quot; or
[ &quot;user_name = ?&quot;, username ]. See conditions in the intro to <a
href="../Base.html">ActiveRecord::Base</a>.

</li>
<li><tt>:joins</tt>: Either an SQL fragment for additional joins like
&quot;LEFT JOIN comments ON comments.post_id = id&quot; (rarely needed) or
named associations in the same form used for the <tt>:include</tt> option,
which will perform an INNER JOIN on the associated table(s). If the value
is a string, then the records will be returned read-only since they will
have attributes that do not correspond to the table&#8216;s columns. Pass
<tt>:readonly =&gt; false</tt> to override.

</li>
<li><tt>:include</tt>: Named associations that should be loaded alongside using
LEFT OUTER JOINs. The symbols named refer to already defined associations.
When using named associations, <a
href="ClassMethods.html#M001626">count</a> returns the number of DISTINCT
items for the model you&#8216;re counting. See eager loading under
Associations.

</li>
<li><tt>:order</tt>: An SQL fragment like &quot;created_at DESC, name&quot;
(really only used with GROUP BY calculations).

</li>
<li><tt>:group</tt>: An attribute name by which the result should be grouped.
Uses the GROUP BY SQL-clause.

</li>
<li><tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be
changed if you, for example, want to do a join but not include the joined
columns.

</li>
<li><tt>:distinct</tt>: Set this to true to make this a distinct calculation,
such as SELECT COUNT(DISTINCT posts.id) &#8230;

</li>
<li><tt>:from</tt> - By default, this is the table name of the class, but can
be changed to an alternate table name (or even the name of a database
view).

</li>
</ul>
<p>
Examples for counting all:
</p>
<pre>
  Person.count         # returns the total count of all people
</pre>
<p>
Examples for counting by column:
</p>
<pre>
  Person.count(:age)  # returns the total count of all people whose age is present in database
</pre>
<p>
Examples for <a href="ClassMethods.html#M001626">count</a> with options:
</p>
<pre>
  Person.count(:conditions =&gt; &quot;age &gt; 26&quot;)
  Person.count(:conditions =&gt; &quot;age &gt; 26 AND job.salary &gt; 60000&quot;, :include =&gt; :job) # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN.
  Person.count(:conditions =&gt; &quot;age &gt; 26 AND job.salary &gt; 60000&quot;, :joins =&gt; &quot;LEFT JOIN jobs on jobs.person_id = person.id&quot;) # finds the number of rows matching the conditions and joins.
  Person.count('id', :conditions =&gt; &quot;age &gt; 26&quot;) # Performs a COUNT(id)
  Person.count(:all, :conditions =&gt; &quot;age &gt; 26&quot;) # Performs a COUNT(*) (:all is an alias for '*')
</pre>
<p>
Note: <tt>Person.count(:all)</tt> will not work because it will use
<tt>:all</tt> as the condition. Use Person.count instead.
</p>
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001626-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001626-source">
<pre>
    <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/calculations.rb, line 47</span>
47:       <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">count</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">args</span>)
48:         <span class="ruby-identifier">calculate</span>(<span class="ruby-identifier">:count</span>, <span class="ruby-operator">*</span><span class="ruby-identifier">construct_count_options_from_args</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">args</span>))
49:       <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>

      <div id="method-M001629" class="method-detail">
        <a name="M001629"></a>

        <div class="method-heading">
          <a href="#M001629" class="method-signature">
          <span class="method-name">maximum</span><span class="method-args">(column_name, options = {})</span>
          </a>
        </div>
      
        <div class="method-description">
          <p>
Calculates the <a href="ClassMethods.html#M001629">maximum</a> value on a
given column. The value is returned with the same data type of the column.
See <tt><a href="ClassMethods.html#M001631">calculate</a></tt> for examples
with options.
</p>
<pre>
  Person.maximum('age')
</pre>
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001629-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001629-source">
<pre>
    <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/calculations.rb, line 68</span>
68:       <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">maximum</span>(<span class="ruby-identifier">column_name</span>, <span class="ruby-identifier">options</span> = {})
69:         <span class="ruby-identifier">calculate</span>(<span class="ruby-identifier">:max</span>, <span class="ruby-identifier">column_name</span>, <span class="ruby-identifier">options</span>)
70:       <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>

      <div id="method-M001628" class="method-detail">
        <a name="M001628"></a>

        <div class="method-heading">
          <a href="#M001628" class="method-signature">
          <span class="method-name">minimum</span><span class="method-args">(column_name, options = {})</span>
          </a>
        </div>
      
        <div class="method-description">
          <p>
Calculates the <a href="ClassMethods.html#M001628">minimum</a> value on a
given column. The value is returned with the same data type of the column.
See <tt><a href="ClassMethods.html#M001631">calculate</a></tt> for examples
with options.
</p>
<pre>
  Person.minimum('age')
</pre>
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001628-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001628-source">
<pre>
    <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/calculations.rb, line 61</span>
61:       <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">minimum</span>(<span class="ruby-identifier">column_name</span>, <span class="ruby-identifier">options</span> = {})
62:         <span class="ruby-identifier">calculate</span>(<span class="ruby-identifier">:min</span>, <span class="ruby-identifier">column_name</span>, <span class="ruby-identifier">options</span>)
63:       <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>

      <div id="method-M001630" class="method-detail">
        <a name="M001630"></a>

        <div class="method-heading">
          <a href="#M001630" class="method-signature">
          <span class="method-name">sum</span><span class="method-args">(column_name, options = {})</span>
          </a>
        </div>
      
        <div class="method-description">
          <p>
Calculates the <a href="ClassMethods.html#M001630">sum</a> of values on a
given column. The value is returned with the same data type of the column.
See <tt><a href="ClassMethods.html#M001631">calculate</a></tt> for examples
with options.
</p>
<pre>
  Person.sum('age')
</pre>
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001630-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001630-source">
<pre>
    <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/calculations.rb, line 75</span>
75:       <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">sum</span>(<span class="ruby-identifier">column_name</span>, <span class="ruby-identifier">options</span> = {})
76:         <span class="ruby-identifier">calculate</span>(<span class="ruby-identifier">:sum</span>, <span class="ruby-identifier">column_name</span>, <span class="ruby-identifier">options</span>)
77:       <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>

      <h3 class="section-bar">Protected Instance methods</h3>

      <div id="method-M001632" class="method-detail">
        <a name="M001632"></a>

        <div class="method-heading">
          <a href="#M001632" class="method-signature">
          <span class="method-name">construct_count_options_from_args</span><span class="method-args">(*args)</span>
          </a>
        </div>
      
        <div class="method-description">
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001632-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001632-source">
<pre>
     <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/calculations.rb, line 133</span>
133:         <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">construct_count_options_from_args</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">args</span>)
134:           <span class="ruby-identifier">options</span>     = {}
135:           <span class="ruby-identifier">column_name</span> = <span class="ruby-identifier">:all</span>
136:           
137:           <span class="ruby-comment cmt"># We need to handle</span>
138:           <span class="ruby-comment cmt">#   count()</span>
139:           <span class="ruby-comment cmt">#   count(:column_name=:all)</span>
140:           <span class="ruby-comment cmt">#   count(options={})</span>
141:           <span class="ruby-comment cmt">#   count(column_name=:all, options={})</span>
142:           <span class="ruby-keyword kw">case</span> <span class="ruby-identifier">args</span>.<span class="ruby-identifier">size</span>
143:           <span class="ruby-keyword kw">when</span> <span class="ruby-value">1</span>
144:             <span class="ruby-identifier">args</span>[<span class="ruby-value">0</span>].<span class="ruby-identifier">is_a?</span>(<span class="ruby-constant">Hash</span>) <span class="ruby-operator">?</span> <span class="ruby-identifier">options</span> = <span class="ruby-identifier">args</span>[<span class="ruby-value">0</span>] <span class="ruby-operator">:</span> <span class="ruby-identifier">column_name</span> = <span class="ruby-identifier">args</span>[<span class="ruby-value">0</span>]
145:           <span class="ruby-keyword kw">when</span> <span class="ruby-value">2</span>
146:             <span class="ruby-identifier">column_name</span>, <span class="ruby-identifier">options</span> = <span class="ruby-identifier">args</span>
147:           <span class="ruby-keyword kw">else</span>
148:             <span class="ruby-identifier">raise</span> <span class="ruby-constant">ArgumentError</span>, <span class="ruby-node">&quot;Unexpected parameters passed to count(): #{args.inspect}&quot;</span>
149:           <span class="ruby-keyword kw">end</span> <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">args</span>.<span class="ruby-identifier">size</span> <span class="ruby-operator">&gt;</span> <span class="ruby-value">0</span>
150:           
151:           [<span class="ruby-identifier">column_name</span>, <span class="ruby-identifier">options</span>]
152:         <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>


    </div>


  </div>


<div id="validator-badges">
  <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>

</body>
</html>